import {
  Component,
  OnInit,
  HostBinding,
  Input,
  Optional,
  HostListener,
  OnDestroy,
  ContentChild,
  TemplateRef,
  AfterContentInit,
  ElementRef,
} from '@angular/core';

import { MenuComponent } from './menu.component';
import { SubMenuComponent } from './sub-menu.component';
import { MenuStateService } from './menu-state.service';

@Component({
  selector: 'fui-menu-item',
  templateUrl: './menu-item.component.html',
})
export class MenuItemComponent implements OnInit, OnDestroy {
  @HostBinding('class.fui-menu-item') hostClass = true;

  // 是否折叠
  @HostBinding('class.collapsed') get collapsedClass() {
    return this.collapsed;
  }

  // 是否嵌套在submenu里
  @HostBinding('class.nested') get nestedClass() {
    return this.submenu;
  }

  // submenu是否折叠，导致menu-item缩小
  @HostBinding('class.mini') get miniClass() {
    return this.submenu && this.submenu.childrenCollapsed;
  }

  // 是否选择高亮
  @HostBinding('class.active') get activeClass() {
    return this.state.isActive(this.key);
  }

  @HostBinding('style.padding-left') get paddingLeft() {
    if (this.submenu && this.submenu.mode === 'foldable' && !this.miniClass) {
      return (1.5 + 1.75) + 'rem';
    }
  }

  /** Menu item icon. */
  @Input() icon: string;

  /** Menu item key. */
  @Input() key: string;

  /** Avatar text. */
  @Input() set avatarText(text: string) {
    if (text && text.length > 0) {
      this.textHead = text[0];
    }
  }

  /** Optional menu item template. */
  @Input() menuItemTemplate: TemplateRef<{$implicit: boolean; collapsed: boolean; active: boolean}>;

  textHead = '';

  get collapsed() {
    return !this.submenu && this.menu.collapsed;
  }

  get context() {
    return {
      $implicit: this.collapsed,
      collapsed: this.collapsed,
      active: this.activeClass,
    };
  }

  @HostListener('click') click() {
    this.state.select(this.key);
  }

  constructor(
    private menu: MenuComponent,
    @Optional() private submenu: SubMenuComponent,
    private state: MenuStateService,
    public elementRef: ElementRef,
  ) {}

  ngOnInit() {
    const submenuKey = this.submenu && this.submenu.key;
    this.state.register(this.key, submenuKey);
  }

  ngOnDestroy() {
    const submenuKey = this.submenu && this.submenu.key;
    this.state.unregister(this.key, submenuKey);
  }
}
